package com.entrogy.api;

import com.entrogy.annotation.ThdidRequest;
import com.entrogy.bean.*;
import com.entrogy.dao.ParentMapper;
import com.entrogy.dao.SchoolMapper;
import com.entrogy.dao.StudentMapper;
import com.entrogy.dao.UserMapper;
import com.entrogy.timing.ChangePersonTimeThread;
import com.entrogy.timing.TimingTaskService;
import com.entrogy.utils.PicUtils;
import com.entrogy.utils.StrUtils;
import com.entrogy.utils.THDio;
import com.entrogy.utils.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName ThdidPersonApi 实义德人员信息相关api和我们信息的转换层
 * @Description
 * @Author luoxingjiang
 * @Date 2020-03-16 下午 6:24
 * @Version 1.0
 **/
@Component
@Slf4j
public class ThdidPersonApi {

    @Value("${image.storage.host}")
    private String imageHost;

    @Value("${image.storage.port}")
    private String hostPort;

    @Value("${show.image.url}")
    private String showImage;

    @Autowired
    private THDio thDio;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SchoolMapper schoolMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ParentMapper parentMapper;


    /**
     * 从实义德后台删除人员
     *
     * @param systemId    人员在我们系统内的id
     * @param schoolCode  学校编码
     * @param deviceModel 设备
     * @param personType  人员类型：1表示教师，2表示学生，3表示家长
     * @return
     * @throws Exception
     */
    @ThdidRequest(value = Constants.THDID_PERSON_DELETE_URL)
    public boolean deletePerson(String systemId, Integer schoolCode, String deviceModel, int personType) throws Exception {
        JSONObject params = new JSONObject();
        Integer thdidId = null;
        String personName = null;
        // 判断人员类型
        switch (personType) {
            case Constants.TEACHER_TYPE:
                UserEntity user = userMapper.getUserByUid(systemId);
                if (user != null) {
                    personName = user.getName();
                    if (Constants.THDID_AI06.equals(deviceModel)) {
                        thdidId = user.getUserThdid();
                    } else if (Constants.THDID_AI16.equals(deviceModel)) {
                        thdidId = user.getTeacherThdidAi16Id();
                    }
                }
                break;
            case Constants.STUDENT_TYPE:
                StudentEntity student = studentMapper.getStudentById(Integer.valueOf(systemId));
                if (student != null) {
                    personName = student.getStudentName();
                    if (Constants.THDID_AI06.equals(deviceModel)) {
                        thdidId = student.getStudentThdid();
                    } else if (Constants.THDID_AI16.equals(deviceModel)) {
                        thdidId = student.getStudentThdidAi16Id();
                    }
                }
                break;
            case Constants.PARENT_TYPE:
                ParentBasicEntity parent = parentMapper.getParent(systemId);
                if (parent != null) {
                    personName = parent.getParentVisitorName();
                    if (Constants.THDID_AI06.equals(deviceModel)) {
                        thdidId = parent.getParentThdidAi06Id();
                    } else if (Constants.THDID_AI16.equals(deviceModel)) {
                        thdidId = parent.getParentThdidAi16Id();
                    }
                }
                break;
        }
        if (thdidId == null) {
            log.warn("删除实义德后台：{}的人员时，人员：{}的实义德ID不存在", deviceModel, personName);
            return false;
        }
        params.put("personnel_id", thdidId);
        params.put("type", 1);// 删除类型 0: 放入未分组 1:删除
        SchoolThdidUrlEntity schoolThdidUrl = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, deviceModel);
        if (schoolThdidUrl == null) {
            log.warn("学校：{}对应的设备：{}实义德后台不存在", schoolCode, deviceModel);
            return false;
        }
        log.info("实义德后台：{}，删除人员：{}开始", deviceModel, personName);
        JSONObject res = thDio.THD_interface(schoolThdidUrl.getPathUrl(), Constants.THDID_PERSON_DELETE_URL, params, false, schoolThdidUrl.getAccessToken());
        log.info("实义德后台：{}，删除人员: {}结果", deviceModel, res.toString());
        if (res.getInt("code") == 0) {
            return true;
        }
        return false;
    }

    /**
     * 从实义德所有后台删除人员
     *
     * @param systemId
     * @param schoolCode
     * @return
     */
    public boolean deletePersontToAll(String systemId, Integer schoolCode, int personType) {
        try {
            deletePerson(systemId, schoolCode, Constants.THDID_AI06, personType);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("人员ID：{}，添加到实义德：{}后台时出错", systemId, Constants.THDID_AI06);
        }
        try {
            deletePerson(systemId, schoolCode, Constants.THDID_AI16, personType);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("人员ID：{}，添加到实义德：{}后台时出错", systemId, Constants.THDID_AI16);
        }
        return true;
    }


    /**
     * 添加家长到学校对应的某个后台
     *
     * @param parent
     * @param schoolCode
     * @param deviceModel
     * @return
     * @throws Exception
     */
    @ThdidRequest(value = Constants.THDID_PERSON_ADD_URL)
    public Integer addParent(ParentBasicEntity parent, Integer schoolCode, String deviceModel) throws Exception {
        SchoolThdidUrlEntity schoolThdidUrl = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, deviceModel);
        if (schoolThdidUrl == null) {
            log.warn("学校：{}对应的设备：{}实义德后台不存在", schoolCode, deviceModel);
            return null;
        }
        JSONObject params = null;
        try {
            params = convertToThdidPerson(parent, schoolThdidUrl, false);
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
        Integer thdId = null;// 实义德ID
        log.info("实义德后台：{}添加家长：{}开始", deviceModel, parent.getParentVisitorName());
        JSONObject res = thDio.THD_interface(schoolThdidUrl.getPathUrl(), Constants.THDID_PERSON_ADD_URL, params, false, schoolThdidUrl.getAccessToken());
        log.info("实义德后台：{}添加家长结果: {}", deviceModel, res.toString());
        if (res.getInt("code") == 0) {
            thdId = res.getJSONObject("data").getInt("personnel_id");
        }
        return thdId;
    }

    /**
     * 添加家长到学校对应的所有实义德后台
     *
     * @param parent
     * @param schoolCode
     * @return
     * @throws Exception
     */
    public Map<String, Integer> addParentToAll(ParentBasicEntity parent, Integer schoolCode) {
        Map<String, Integer> thdidInfo = new HashMap<>();
        Integer parentThdidAi06Id = null;
        Integer parentThdidAi16Id = null;
        try {
            if (parent.getParentThdidAi06Id() == null || parent.getParentThdidAi06Id() == 0)
                parentThdidAi06Id = addParent(parent, schoolCode, Constants.THDID_AI06);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("家长：{}，添加到实义德：{}后台时出错", parent, Constants.THDID_AI06);
        }
        try {
            if (parent.getParentThdidAi16Id() == null || parent.getParentThdidAi16Id() == 0)
                parentThdidAi16Id = addParent(parent, schoolCode, Constants.THDID_AI16);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("家长：{}，添加到实义德：{}后台时出错", parent, Constants.THDID_AI16);
        }
        thdidInfo.put("parentThdidAi06Id", parentThdidAi06Id);
        thdidInfo.put("parentThdidAi16Id", parentThdidAi16Id);
        return thdidInfo;
    }

    /**
     * 更新某个后台的家长信息
     *
     * @param parent
     * @param schoolCode
     * @param deviceModel
     * @return
     * @throws Exception
     */
    @ThdidRequest(value = Constants.THDID_PERSON_UPDATE_URL)
    public Boolean updateParent(ParentBasicEntity parent, Integer schoolCode, String deviceModel) throws Exception {
        SchoolThdidUrlEntity schoolThdidUrl = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, deviceModel);
        if (schoolThdidUrl == null) {
            log.warn("学校：{}对应的设备：{}实义德后台不存在", schoolCode, deviceModel);
            return null;
        }
        JSONObject params = null;
        try {
            params = convertToThdidPerson(parent, schoolThdidUrl, true);
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
        log.info("实义德后台：{}修改家长：{}开始", deviceModel, parent.getParentVisitorName());
        JSONObject res = thDio.THD_interface(schoolThdidUrl.getPathUrl(), Constants.THDID_PERSON_UPDATE_URL, params, false, schoolThdidUrl.getAccessToken());
        log.info("实义德后台：{}修改家长结果: {}", deviceModel, res.toString());
        return res.getInt("code") == 0 ? true : false;
    }


    /**
     * 更新所有实义德后台的家长信息
     *
     * @param parent
     * @param schoolCode
     * @return 有可能修改时新增，所以会返回map中有新增后的id
     */
    public Map<String, Integer> updateParentToAll(ParentBasicEntity parent, Integer schoolCode) {
        Map<String, Integer> map = new HashMap<>();
        ParentBasicEntity parentFromDB = parentMapper.getParent(parent.getParentVisitorId());
        Integer parentThdidAi06Id = parentFromDB.getParentThdidAi06Id();
        if (parentThdidAi06Id != null && parentThdidAi06Id != 0) {   // 学生事先录入过照片，直接修改实义德AI06后台照片即可
            // 兼容实义德新接口的实体类
            parent.setParentThdidAi06Id(parentThdidAi06Id);
            try {
                updateParent(parent, schoolCode, Constants.THDID_AI06);
            } catch (Exception e) {
                log.error("家长：{}，修改实义德：{}后台的信息时出错", parent, Constants.THDID_AI06);
            }
        } else if (StringUtils.isNoneBlank(parent.getParentVisitorBase64())) {// 学生之前没有录入过照片，需要在实义德后台添加这个学生
            parent.setIcNumber(parent.getIcNumber() == null ? parentFromDB.getIcNumber() : parent.getIcNumber());
            parent.setParentVisitorName(parent.getParentVisitorName() == null ? parentFromDB.getParentVisitorName() : parent.getParentVisitorName());
            parent.setParentVisitorBase64(parent.getParentVisitorBase64() == null ? parentFromDB.getParentVisitorBase64() : parent.getParentVisitorBase64());
            parent.setGender(parentFromDB.getGender());
            parent.setIdNumber(parent.getIdNumber() == null ? parentFromDB.getIdNumber() : parent.getIdNumber());
            try {
                parentThdidAi06Id = addParent(parent, schoolCode, Constants.THDID_AI06);
            } catch (Exception e) {
                log.error("家长：{}，添加到实义德：{}后台时出错", parent, Constants.THDID_AI06);
            }
        }
        Integer parentThdidAi16Id = parentFromDB.getParentThdidAi16Id();
        if (parentThdidAi16Id != null && parentThdidAi16Id != 0) {
            // 兼容实义德新接口的实体类
            parent.setParentThdidAi06Id(parentFromDB.getParentThdidAi16Id());
            try {
                updateParent(parent, schoolCode, Constants.THDID_AI16);
            } catch (Exception e) {
                log.error("家长：{}，修改实义德：{}后台的信息时出错", parent.getParentVisitorName(), Constants.THDID_AI06);
            }
        } else if (StringUtils.isNoneBlank(parentFromDB.getParentVisitorBase64())) {
            parent.setIcNumber(parent.getIcNumber() == null ? parentFromDB.getIcNumber() : parent.getIcNumber());
            parent.setParentVisitorName(parent.getParentVisitorName() == null ? parentFromDB.getParentVisitorName() : parent.getParentVisitorName());
            parent.setParentVisitorBase64(parent.getParentVisitorBase64() == null ? parentFromDB.getParentVisitorBase64() : parent.getParentVisitorBase64());
            parent.setGender(parentFromDB.getGender());
            parent.setIdNumber(parent.getIdNumber() == null ? parentFromDB.getIdNumber() : parent.getIdNumber());
            try {
                parentThdidAi16Id = addParent(parent, schoolCode, Constants.THDID_AI16);
            } catch (Exception e) {
                log.error("家长：{}，添加到实义德：{}后台时出错", parent.getParentVisitorName(), Constants.THDID_AI06);
            }
        }
        map.put("parentThdidAi16Id", parentThdidAi16Id);
        map.put("parentThdidAi06Id", parentThdidAi06Id);
        return map;
    }


    /**
     * 添加学生到某个后台
     *
     * @param student
     * @param schoolCode
     * @param deviceModel
     * @return
     * @throws Exception
     */
    @ThdidRequest(value = Constants.THDID_PERSON_ADD_URL)
    public Integer addStudent(StudentBaseEntity student, Integer schoolCode, String deviceModel) throws Exception {
        SchoolThdidUrlEntity schoolThdidUrl = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, deviceModel);
        if (schoolThdidUrl == null) {
            log.warn("学校：{}对应的设备：{}实义德后台不存在", schoolCode, deviceModel);
            return null;
        }
        JSONObject params = null;
        try {
            params = convertToThdidPerson(student, schoolThdidUrl, false);
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
        Integer thdId = null;// 实义德ID
        log.info("实义德后台：{}添加学生：{}开始", deviceModel, student.getStudentName());
        JSONObject res = thDio.THD_interface(schoolThdidUrl.getPathUrl(), Constants.THDID_PERSON_ADD_URL, params, false, schoolThdidUrl.getAccessToken());
        log.info("实义德后台：{}添加学生结果: {}", deviceModel, res.toString());
        if (res.getInt("code") == 0) {
            thdId = res.getJSONObject("data").getInt("personnel_id");
        }
        return thdId;
    }

    /**
     * 添加学生到学校对应的所有实义德后台
     *
     * @param student
     * @param schoolCode
     * @return
     * @throws Exception
     */
    public Map<String, Integer> addStudentToAll(StudentBaseEntity student, Integer schoolCode) {
        Map<String, Integer> thdidInfo = new HashMap<>();
        Integer studentThdidAi06Id = null;
        Integer studentThdidAi16Id = null;
        try {
            if (student.getStudentAi06ThdidId() == null || student.getStudentAi06ThdidId() == 0)
                studentThdidAi06Id = addStudent(student, schoolCode, Constants.THDID_AI06);
        } catch (Exception e) {
            log.error("学生：{}，添加到实义德：{}后台时出错", student, Constants.THDID_AI06);
        }
        try {
            if (student.getStudentAi16ThdidId() == null || student.getStudentAi16ThdidId() == 0)
                studentThdidAi16Id = addStudent(student, schoolCode, Constants.THDID_AI16);
        } catch (Exception e) {
            log.error("学生：{}，添加到实义德：{}后台时出错", student, Constants.THDID_AI16);
        }
        thdidInfo.put("studentThdidAi06Id", studentThdidAi06Id);
        thdidInfo.put("studentThdidAi16Id", studentThdidAi16Id);
        return thdidInfo;
    }

    /**
     * 更新某个后台的学生信息
     *
     * @param student
     * @param schoolCode
     * @param deviceModel
     * @return
     * @throws Exception
     */
    @ThdidRequest(value = Constants.THDID_PERSON_UPDATE_URL)
    public Boolean updateStudent(StudentBaseEntity student, Integer schoolCode, String deviceModel) throws Exception {
        SchoolThdidUrlEntity schoolThdidUrl = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, deviceModel);
        if (schoolThdidUrl == null) {
            log.warn("学校：{}对应的设备：{}实义德后台不存在", schoolCode, deviceModel);
            return null;
        }
        JSONObject params;
        try {
            params = convertToThdidPerson(student, schoolThdidUrl, true);
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
        log.info("实义德后台：{}修改学生：{}开始", deviceModel, student.getStudentName());
        JSONObject res = thDio.THD_interface(schoolThdidUrl.getPathUrl(), Constants.THDID_PERSON_UPDATE_URL, params, false, schoolThdidUrl.getAccessToken());
        log.info("实义德后台：{}修改学生结果: {}", deviceModel, res.toString());
        return res.getInt("code") == 0 ? true : false;
    }

    /**
     * 更新所有实义德后台的学生信息
     *
     * @param student
     * @param schoolCode
     * @return
     * @throws Exception
     */
    public Map<String, Integer> updateStudentToAll(StudentBaseEntity student, Integer schoolCode) {
        StudentEntity studentFromDB = studentMapper.getStudentById(student.getStudentId());
        Integer studentThdidId = studentFromDB.getStudentThdid();
        if (studentThdidId != null && studentThdidId != 0) {   // 学生事先录入过照片，直接修改实义德AI06后台照片即可
            // 兼容实义德新接口的实体类
            student.setStudentAi06ThdidId(studentThdidId);
            try {
                updateStudent(student, schoolCode, Constants.THDID_AI06);
            } catch (Exception e) {
                log.error("学生：{}，修改实义德：{}后台的信息时出错", student, Constants.THDID_AI06);
            }
        } else if (StringUtils.isNoneBlank(studentFromDB.getStudentBase64())) {// 学生之前没有录入过照片，需要在实义德后台添加这个学生
            student.setIcNumber(student.getIcNumber() == null ? studentFromDB.getIcNumber() : student.getIcNumber())
                    .setStudentName(student.getStudentName() == null ? studentFromDB.getStudentName() : student.getStudentName())
                    .setPhotoUrl(student.getPhotoUrl() == null ? studentFromDB.getStudentBase64() : student.getPhotoUrl())
                    .setGender(studentFromDB.getSex())
                    .setIdNumber(student.getIdNumber() == null ? studentFromDB.getIdNumber() : student.getIdNumber());
            try {
                studentThdidId = addStudent(student, schoolCode, Constants.THDID_AI06);
            } catch (Exception e) {
                log.error("学生：{}，添加到实义德：{}后台时出错", student, Constants.THDID_AI06);
            }
        }
        Integer studentThdidAi16Id = studentFromDB.getStudentThdidAi16Id();
        if (studentThdidAi16Id != null && studentThdidAi16Id != 0) {
            // 兼容实义德新接口的实体类
            student.setStudentAi16ThdidId(studentFromDB.getStudentThdidAi16Id());
            try {
                updateStudent(student, schoolCode, Constants.THDID_AI16);
            } catch (Exception e) {
                log.error("学生：{}，修改实义德：{}后台的信息时出错", student.getStudentName(), Constants.THDID_AI06);
            }
        } else if (StringUtils.isNoneBlank(studentFromDB.getStudentBase64())) {
            student.setIcNumber(student.getIcNumber() == null ? studentFromDB.getIcNumber() : student.getIcNumber())
                    .setStudentName(student.getStudentName() == null ? studentFromDB.getStudentName() : student.getStudentName())
                    .setPhotoUrl(student.getPhotoUrl() == null ? studentFromDB.getStudentBase64() : student.getPhotoUrl())
                    .setGender(studentFromDB.getSex())
                    .setIdNumber(student.getIdNumber() == null ? studentFromDB.getIdNumber() : student.getIdNumber());
            try {
                studentThdidAi16Id = addStudent(student, schoolCode, Constants.THDID_AI16);
            } catch (Exception e) {
                log.error("学生：{}，添加到实义德：{}后台时出错", student.getStudentName(), Constants.THDID_AI06);
            }
        }
        Map<String, Integer> map = new HashMap<>();
        map.put("studentThdidAi06Id", studentThdidId);
        map.put("studentThdidAi16Id", studentThdidAi16Id);
        return map;
    }

    @ThdidRequest(value = Constants.THDID_PERSON_ADD_URL)
    public Integer addTeacher(TeacherBasicInfoEntity teacher, Integer schoolCode, String deviceModel) throws Exception {
        SchoolThdidUrlEntity schoolThdidUrl = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, deviceModel);
        if (schoolThdidUrl == null) {
            log.warn("学校：{}对应的设备：{}实义德后台不存在", schoolCode, deviceModel);
            return null;
        }
        Integer thdId = null;// 实义德ID
        JSONObject params = null;
        try {
            params = convertToThdidPerson(teacher, schoolThdidUrl, false);
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
        log.info("实义德后台：{}添加教师：{}开始", deviceModel, teacher.getTeacherName());
        JSONObject res = thDio.THD_interface(schoolThdidUrl.getPathUrl(), Constants.THDID_PERSON_ADD_URL, params, false, schoolThdidUrl.getAccessToken());
        log.info("实义德后台：{}添加教师结果: {}", deviceModel, res.toString());
        if (res.getInt("code") == 0) {
            thdId = res.getJSONObject("data").getInt("personnel_id");
        }
        switch (schoolThdidUrl.getDeviceModel()) {
            case Constants.THDID_AI06:
                teacher.setTeacherThdidAi06Id(thdId);
                // 推送教师在相应实义德后台的权限
                pushPerson(thdId, schoolThdidUrl, Constants.THDID_AI06, null, null, null, "推送教师");
                break;
            case Constants.THDID_AI16:
                teacher.setTeacherThdidAi16Id(thdId);
                // 推送教师在相应实义德后台的权限
                pushPerson(thdId, schoolThdidUrl, Constants.THDID_AI16, null, null, null, "推送教师");
                break;
        }
        if (teacher.getTeacherThdidAi06Id() != null || teacher.getTeacherThdidAi16Id() != null) {
            int updateUserDetail = userMapper.updateUserDetail(teacher);
            if (updateUserDetail != 1) {
                log.error("更新教师：{}的实义德id失败", teacher);
            }
        }
        return thdId;
    }

    /**
     * 教师添加到所有实义德后台
     *
     * @param teacher
     * @param schoolCode
     */
    public Map<String, Integer> addTeacherToAll(TeacherBasicInfoEntity teacher, Integer schoolCode) {
        Map<String, Integer> thdidInfo = new HashMap<>();
        Integer teacherThdidAi06Id = null;
        Integer teacherThdidAi16Id = null;
        if (teacher.getTeacherThdidAi06Id() == null || teacher.getTeacherThdidAi06Id() == 0) {
            try {
                teacherThdidAi06Id = addTeacher(teacher, schoolCode, Constants.THDID_AI06);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("教师：{}，添加到实义德：{}后台时出错", teacher.getTeacherName(), Constants.THDID_AI06);
            }
        }
        if (teacher.getTeacherThdidAi16Id() == null || teacher.getTeacherThdidAi16Id() == 0) {
            try {
                teacherThdidAi16Id = addTeacher(teacher, schoolCode, Constants.THDID_AI16);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("教师：{}，添加到实义德：{}后台时出错", teacher.getTeacherName(), Constants.THDID_AI16);
            }
        }
        thdidInfo.put("teacherThdidAi06Id", teacherThdidAi06Id);
        thdidInfo.put("teacherThdidAi16Id", teacherThdidAi16Id);
        return thdidInfo;
    }

    /**
     * 新增人员时推送权限至相应的后台
     *
     * @param thdId
     * @param schoolThdidUrl
     * @param startTime
     * @param endTime
     * @param desc
     */
    public void pushPerson(Integer thdId, SchoolThdidUrlEntity schoolThdidUrl, String deviceModel, Long startTime, Long endTime, Integer cycleId, String desc) {
        String deviceIds = new TimingTaskService().getDeviceIds(false, schoolThdidUrl.getSchoolCode(), deviceModel);// 获取该学校的所有闸机设备
        if (StringUtils.isNoneBlank(deviceIds)) {
            ChangePersonTimeThread changePersonTimeThread = new ChangePersonTimeThread(deviceIds, String.valueOf(thdId), 1,
                    cycleId == null ? 1 : cycleId, "全体all", 999999, startTime == null ? 111111111L : startTime,
                    endTime == null ? 99999999999L : endTime, desc, 0, schoolThdidUrl.getPathUrl(), schoolThdidUrl.getAccessToken());
            changePersonTimeThread.start();
        }
    }

    /**
     * 新增人员时推送权限至所有的后台
     *
     * @param thdidAi06Id
     * @param thdidAi16Id
     */
    public void pushPersonToAll(Integer thdidAi06Id, Integer thdidAi16Id, Integer schoolCode, Long startTime, Long endTime, Integer cycleId, String desc) {
        SchoolThdidUrlEntity schoolThdidAi06Url = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI06);
        if (schoolThdidAi06Url != null) {
            pushPerson(thdidAi06Id, schoolThdidAi06Url, Constants.THDID_AI06, startTime, endTime, cycleId, desc);
        }
        SchoolThdidUrlEntity schoolThdidAi16Url = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI16);
        if (schoolThdidAi16Url != null) {
            pushPerson(thdidAi16Id, schoolThdidAi16Url, Constants.THDID_AI16, startTime, endTime, cycleId, desc);
        }
    }

    /**
     * 更新某个实义德后台的教师信息
     *
     * @param teacher
     * @param schoolCode
     * @param deviceModel
     * @return
     * @throws Exception
     */
    @ThdidRequest(value = Constants.THDID_PERSON_UPDATE_URL)
    public Boolean updateTeacher(TeacherBasicInfoEntity teacher, Integer schoolCode, String deviceModel) throws Exception {
        SchoolThdidUrlEntity schoolThdidUrl = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, deviceModel);
        if (schoolThdidUrl == null) {
            log.warn("学校：{}对应的设备：{}实义德后台不存在", schoolCode, deviceModel);
            return null;
        }
        JSONObject params;
        try {
            params = convertToThdidPerson(teacher, schoolThdidUrl, true);
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }
        log.info("实义德后台：{}, 修改教师：{}开始", deviceModel, teacher.getTeacherName());
        JSONObject res = thDio.THD_interface(schoolThdidUrl.getPathUrl(), Constants.THDID_PERSON_UPDATE_URL, params, false, schoolThdidUrl.getAccessToken());
        log.info("实义德后台：{}修改教师结果: {}", deviceModel, res.toString());
        return res.getInt("code") == 0 ? true : false;
    }

    /**
     * 更新所有实义德后台的教师信息
     *
     * @param teacher
     * @param schoolCode
     * @return
     * @throws Exception
     */
    public void updateTeacherToAll(TeacherBasicInfoEntity teacher, Integer schoolCode) {
        UserEntity teacherFromDB = userMapper.getUserByUid(teacher.getTeacherId());
        Integer teacherThdidAi06Id = teacherFromDB.getUserThdid();
        if (teacherThdidAi06Id != 0) {   // 教师事先录入过照片，直接修改实义德AI06后台照片即可
            // 兼容实义德新接口的实体类
            teacher.setTeacherThdidAi06Id(teacherThdidAi06Id);
            try {
                updateTeacher(teacher, schoolCode, Constants.THDID_AI06);
            } catch (Exception e) {
                log.error("教师：{}，修改实义德：{}后台的信息时出错", teacher, Constants.THDID_AI06);
            }
        } else if (StringUtils.isNoneBlank(teacherFromDB.getPhoto())) {// 教师之前没有录入过照片，需要在实义德后台添加这个教师
            teacher.setIcNumber(teacher.getIcNumber() == null ? teacherFromDB.getIcNumber() : teacher.getIcNumber())
                    .setTeacherName(teacher.getTeacherName() == null ? teacherFromDB.getName() : teacher.getTeacherName())
                    .setPhoto(teacher.getPhoto() == null ? teacherFromDB.getPhoto() : teacher.getPhoto())
                    .setGender(teacherFromDB.getSex())
                    .setIdNumber(teacher.getIdNumber() == null ? teacherFromDB.getIdNumber() : teacher.getIdNumber());
            try {
                addTeacher(teacher, schoolCode, Constants.THDID_AI06);
            } catch (Exception e) {
                log.error("教师：{}，添加到实义德：{}后台时出错", teacher, Constants.THDID_AI06);
            }
        }
        if (teacherFromDB.getTeacherThdidAi16Id() != null) {
            // 兼容实义德新接口的实体类
            teacher.setTeacherThdidAi16Id(teacherFromDB.getTeacherThdidAi16Id());
            try {
                updateTeacher(teacher, schoolCode, Constants.THDID_AI16);
            } catch (Exception e) {
                log.error("教师：{}，修改实义德：{}后台的信息时出错", teacher, Constants.THDID_AI06);
            }
        } else if (StringUtils.isNoneBlank(teacherFromDB.getPhoto())) {
            teacher.setIcNumber(teacher.getIcNumber() == null ? teacherFromDB.getIcNumber() : teacher.getIcNumber())
                    .setTeacherName(teacher.getTeacherName() == null ? teacherFromDB.getName() : teacher.getTeacherName())
                    .setPhoto(teacher.getPhoto() == null ? teacherFromDB.getPhoto() : teacher.getPhoto())
                    .setGender(teacherFromDB.getSex())
                    .setIdNumber(teacher.getIdNumber() == null ? teacherFromDB.getIdNumber() : teacher.getIdNumber());
            try {
                addTeacher(teacher, schoolCode, Constants.THDID_AI16);
            } catch (Exception e) {
                log.error("教师：{}，添加到实义德：{}后台时出错", teacher, Constants.THDID_AI06);
            }
        }

    }

    /**
     * 将相应的人员信息转换为实义德的人员信息
     *
     * @param person
     * @param schoolThdidUrl
     * @param isUpdate       是否是更新操作，更新操作的话，参数的添加规则会有变化
     * @return
     */
    private JSONObject convertToThdidPerson(Object person, SchoolThdidUrlEntity schoolThdidUrl, boolean isUpdate) throws Exception {
        JSONObject params = new JSONObject();
        Integer personThdid = null;
        String icNumber = "";
        String idNumber = "";
        String name = "";
        String phoneNumber = "";
        String photo = "";
        Integer groupId = null;
        params.put("gender", 0);
        if (person instanceof StudentBaseEntity) {
            StudentBaseEntity student = (StudentBaseEntity) person;
            if (Constants.THDID_AI06.equals(schoolThdidUrl.getDeviceModel())) {
                personThdid = student.getStudentAi06ThdidId();
            } else if (Constants.THDID_AI16.equals(schoolThdidUrl.getDeviceModel())) {
                personThdid = student.getStudentAi16ThdidId();
            }
            icNumber = student.getIcNumber();
            idNumber = student.getIdNumber();
            name = student.getStudentName();
            phoneNumber = student.getPhoneNumber();
            photo = student.getPhotoUrl();
            groupId = schoolThdidUrl.getStudentGroupId();
        } else if (person instanceof TeacherBasicInfoEntity) {
            TeacherBasicInfoEntity teacher = (TeacherBasicInfoEntity) person;
            if (Constants.THDID_AI06.equals(schoolThdidUrl.getDeviceModel())) {
                personThdid = teacher.getTeacherThdidAi06Id();
            } else if (Constants.THDID_AI16.equals(schoolThdidUrl.getDeviceModel())) {
                personThdid = teacher.getTeacherThdidAi16Id();
            }
            icNumber = teacher.getIcNumber();
            idNumber = teacher.getIdNumber();
            name = teacher.getTeacherName();
            phoneNumber = teacher.getMobile();
            photo = teacher.getPhoto();
            groupId = schoolThdidUrl.getTeacherGroupId();
        } else if (person instanceof ParentBasicEntity) {
            ParentBasicEntity parent = (ParentBasicEntity) person;
            if (Constants.THDID_AI06.equals(schoolThdidUrl.getDeviceModel())) {
                personThdid = parent.getParentThdidAi06Id();
            } else if (Constants.THDID_AI16.equals(schoolThdidUrl.getDeviceModel())) {
                personThdid = parent.getParentThdidAi16Id();
            }
            icNumber = parent.getIcNumber();
            idNumber = parent.getIdNumber();
            name = parent.getParentVisitorName();
            phoneNumber = parent.getParentVisitorPhone();
            photo = parent.getParentVisitorBase64();
            groupId = schoolThdidUrl.getParentGroupId();
        }
        if (isUpdate) {
            params.put("personnel_id", personThdid);
            if (StringUtils.isNoneBlank(icNumber)) {
                params.put("ic_number", icNumber);
            }
            if (StringUtils.isNoneBlank(idNumber)) {
                params.put("id_number", idNumber);
            }
            if (StringUtils.isNoneBlank(name)) {
                params.put("name", name);
            }
            if (StringUtils.isNoneBlank(phoneNumber)) {
                params.put("phonenumber", phoneNumber);
            }
            if (StringUtils.isNoneBlank(photo)) {
                params.put("base_image", PicUtils.openFileBase64(imageHost + ":" + hostPort + File.separator + showImage
                        + File.separator + photo));
                params.put("cover_type", 2);
//                if (Constants.THDID_AI16.equals(schoolThdidUrl.getDeviceModel()))
//                    params.put("base_image_mask", PicUtils.openFileBase64(imageHost + ":" + hostPort + File.separator + showImage
//                        + File.separator + photo));
            }
        } else {
            params.put("group_id", groupId);
            params.put("ic_number", icNumber);
            params.put("id_number", idNumber);
            params.put("name", name);
            params.put("phonenumber", phoneNumber);
            String base64 = PicUtils.openFileBase64(imageHost + ":" + hostPort + File.separator + showImage
                    + File.separator + photo);
            if (!StringUtils.isNoneBlank(base64)) {
                throw new RuntimeException("推送人员：" + name + "到实义德后台：" + schoolThdidUrl.getPathUrl() + "时照片没有找到");
            }
            params.put("base_image", base64);
//            if (Constants.THDID_AI16.equals(schoolThdidUrl.getDeviceModel()))
//                params.put("base_image_mask", PicUtils.openFileBase64(imageHost + ":" + hostPort + File.separator + showImage
//                        + File.separator + photo));
        }
        return params;
    }

    /**
     * 查询所有学校测温后台的通行记录
     */
    public JSONArray listTemperature (){
        JSONArray temperatureList = new JSONArray();
        List<Integer> schoolCodeList = schoolMapper.listSchoolCode();
        JSONObject params = new JSONObject();
        params.put("page", 1);
        params.put("amount", 500);
        for (Integer schoolCode : schoolCodeList){
            SchoolThdidUrlEntity schoolThdidUrl = schoolMapper.getSchoolThdidUrlAndGroupInfo(schoolCode, Constants.THDID_AI16);
            if (schoolThdidUrl == null || !StringUtils.isNoneBlank(schoolThdidUrl.getPathUrl()) || !StringUtils.isNoneBlank(schoolThdidUrl.getAccessToken())){
                continue;
            }
            try {
                JSONObject jsonObject = thDio.THD_interface(schoolThdidUrl.getPathUrl(), "/record/list", params, true, schoolThdidUrl.getAccessToken());
                JSONObject data = jsonObject.getJSONObject("data");
                JSONArray jsonarray = JSONArray.fromObject(data.get("record_list"));
                temperatureList.addAll(jsonarray);
            } catch (Exception e) {
                log.error("统计学校：{}的体温流水信息时出错！", schoolCode);
                continue;
            }
        }
        return temperatureList;
    }


    @Async("taskExecutor")
    public void asyncAddStudentToAllThdid(StudentEntity studentEntity, Integer schoolCode) {
        log.info("当前线程为：{}", Thread.currentThread());
        StudentBaseEntity student = new StudentBaseEntity();
        student.setIcNumber(studentEntity.getIcNumber())
                .setIdNumber(studentEntity.getIdNumber()).setGender(0)
                .setPhotoUrl(studentEntity.getStudentBase64())
                .setStudentName(studentEntity.getStudentName())
                .setStudentAi06ThdidId(studentEntity.getStudentThdid())
                .setStudentAi16ThdidId(studentEntity.getStudentThdidAi16Id())
                .setStudentId(studentEntity.getId());
        Map<String, Integer> thdidInfo = addStudentToAll(student, schoolCode);
        Integer studentThdidAi06Id = thdidInfo.get("studentThdidAi06Id");
        Integer studentThdidAi16Id = thdidInfo.get("studentThdidAi16Id");
        if (studentThdidAi06Id != null || studentThdidAi16Id != null) {
            StudentEntity updateStudent = new StudentEntity();
            updateStudent.setId(studentEntity.getId());
            updateStudent.setStudentThdid(studentThdidAi06Id == null ? 0 : studentThdidAi06Id);//设置实义德的AI06的后台id
            updateStudent.setStudentThdidAi16Id(studentThdidAi16Id);
            studentMapper.updateStudent(updateStudent);
        }
    }

    @Async("taskExecutor")
    public void asyncAddStudent(StudentEntity studentEntity, Integer schoolCode, String deviceModel) {
        log.info("当前线程为：{}", Thread.currentThread());
        StudentBaseEntity student = new StudentBaseEntity();
        student.setIcNumber(studentEntity.getIcNumber())
                .setIdNumber(studentEntity.getIdNumber()).setGender(0)
                .setPhotoUrl(studentEntity.getStudentBase64())
                .setStudentName(studentEntity.getStudentName())
                .setStudentAi06ThdidId(studentEntity.getStudentThdid())
                .setStudentAi16ThdidId(studentEntity.getStudentThdidAi16Id())
                .setStudentId(studentEntity.getId());
        Integer thdid = null;
        try {
            if ((Constants.THDID_AI06.equals(deviceModel) && studentEntity.getStudentThdid() == 0) || (Constants.THDID_AI16.equals(deviceModel) && studentEntity.getStudentThdidAi16Id() == null))
                thdid = addStudent(student, schoolCode, deviceModel);
        } catch (Exception e) {
            log.error("学生：{}，添加到实义德：{}后台时出错", student, deviceModel);
            return;
        }
        if (thdid != null) {
            StudentEntity updateStudent = new StudentEntity();
            updateStudent.setId(studentEntity.getId());
            if (Constants.THDID_AI06.equals(deviceModel)) {
                updateStudent.setStudentThdid(thdid);//设置实义德的AI06的后台id
            } else if (Constants.THDID_AI16.equals(deviceModel)) {
                updateStudent.setStudentThdidAi16Id(thdid);
            }
            studentMapper.updateStudent(updateStudent);
        }
    }
}
